package edu.ustb.efws.base.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import edu.ustb.efws.EfwsProperties;
import edu.ustb.efws.base.domain.Sms;
import edu.ustb.efws.base.mapper.SmsMapper;
import edu.ustb.efws.base.service.sms.SmsResult;
import edu.ustb.efws.base.service.sms.SmsSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * 短信服务
 *
 * @author TS Group
 */
@Service
@Transactional(readOnly = true)
public class SmsService {
    private final SmsMapper mapper;
    private final SmsSender smsSender;

    @Autowired
    public SmsService(SmsMapper mapper, EfwsProperties properties,
                      ObjectMapper objectMapper, RestTemplate restTemplate) {

        this.mapper = mapper;
        this.smsSender = new SmsSender(restTemplate, objectMapper, properties);
    }

    /**
     * 发送警告短信
     *
     * @param mobile 手机号
     * @param area 空间位置
     * @param position 点位置
     * @param grade 危险等级
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void send(String mobile, String area, String position, String grade){
        String ordId = orderId();
        Map<String, String> params = new HashMap<>(3, 1);
        params.put("area", area);
        params.put("position", position);
        params.put("riskGrade", grade);
        long id = saveLog(ordId, mobile, area, position, grade);
        SmsResult result = smsSender.SmsResult(ordId, mobile, params);
        mapper.update(id, result.getCode(), result.getErrMsg(), result.isSuccess());
    }

    private String orderId() {
        String uuid = UUID.randomUUID().toString();
        return uuid.replace("-", "");
    }

    private long saveLog(String ordId, String mobile, String area,
                            String position, String grade){

        Sms t = new Sms();
        t.setOrdId(ordId);
        t.setMobile(mobile);
        t.setArea(area);
        t.setPosition(position);
        t.setGrade(grade);
        t.setCreateTime(new Date());
        mapper.insert(t);
        return t.getId();
    }

    public long count(String mobile, String area, String position){
        return mapper.count(mobile, area, position);
    }

    public List<Sms> query(String mobile, String area, String position, int offset, int limit){
        return mapper.find(mobile, area, position, offset, limit);
    }
}
